#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: serializer.py
@contact: zwb15083976291@163.com
@time: 2021/10/10
"""
from collections import OrderedDict
from copy import deepcopy

from rest_framework import serializers

from .mixin import SpecifySerializeFieldsMixin


class SpecifySerializeFieldSerializer(SpecifySerializeFieldsMixin, serializers.Serializer):
    """指定字段通用序列化器"""


class SpecifySerializeFieldModelSerializer(SpecifySerializeFieldsMixin, serializers.ModelSerializer):
    """指定字段模型序列化器"""


class UpdateBaseSerializeMethodMixin(object):

    def to_representation(self, instance):
        data = super().to_representation(instance)
        # 只获取时间字符串前10位数
        if data.get("create_time"):
            data["create_time"] = data.get("create_time")[:10]
        if data.get("update_time"):
            data["update_time"] = data.get("update_time")[:10]
        return data

    def _get_model_data(self, validated_data):
        result_data = dict()
        field_names = [field.attname for field in self.Meta.model._meta.fields]
        for item in validated_data.keys():
            if item in field_names:
                result_data[item] = validated_data[item]
        return result_data

    def select_field_update_obj(self, field='id'):
        assert hasattr(self, '_errors'), '必须在检查之后才能调用此函数'
        assert not self.errors, "错误的参数不能更新对象"
        assert field in self.validated_data, f'必须存在{field}该字段才能调用该方法'
        update_data = self._get_model_data(self.validated_data)
        instance = self.Meta.model.objects.filter(
            id=str(update_data.pop("id") if field == 'id' else update_data.get(field)))
        instance.update(**update_data)
        self.instance = instance[0]  # 给序列器提供 .data 方法的支持
        return instance

    def select_field_delete_obj(self, field='id'):
        assert hasattr(self, '_errors'), '必须在检查之后才能调用此函数'
        assert not self.errors, "错误的参数不能更新对象"
        assert field in self.validated_data, f'必须存在{field}该字段才能调用该方法'
        instance = self.Meta.model.objects.filter(**{field: self.validated_data.get(field)}).first()
        instance.delete()
        self.instance = instance  # 给序列器提供 .data 方法的支持
        return instance


class PaginatorSerializer(SpecifySerializeFieldSerializer):
    pageNum = serializers.IntegerField(min_value=0, default=1)
    pageSize = serializers.IntegerField(min_value=0, default=10)
    search = serializers.CharField(min_length=1)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        ret_data = OrderedDict()
        for key, value in data.items():
            ret_data[key] = value.split("T")[0] if key in ['create_time', 'update_time'] else value
        return ret_data


class SearchSerializer(SpecifySerializeFieldSerializer):
    search = serializers.CharField(min_length=2)
